#!/usr/bin/env python3
"""
WebSocket 日志模块
专门用于记录 WebSocket 相关的日志信息
"""

import time
from typing import Any, Optional

from ..config.logging_config import (get_app_logger, log_performance,
                                     log_websocket_event)

# 获取 WebSocket 专用日志器
ws_logger = get_app_logger("websocket")


class WebSocketLogger:
    """WebSocket 日志管理器"""

    def __init__(self, client_id: str):
        """
        初始化 WebSocket 日志管理器

        Args:
            client_id: 客户端标识
        """
        self.client_id = client_id
        self.start_time = time.time()
        self.msg_stats = {"config": 0, "audio": 0, "control": 0}
        self.audio_bytes_total = 0

    def log_connection(self, remote_address: str, connection_count: int):
        """记录连接事件"""
        log_websocket_event("connect", self.client_id, remote_address=remote_address)
        ws_logger.info(f"🔗 新用户连接: {remote_address}, 当前连接数: {connection_count}")

    def log_disconnect(self, reason: str = "normal"):
        """记录断开连接事件"""
        duration = time.time() - self.start_time
        log_websocket_event("disconnect", self.client_id, reason=reason, duration=duration)
        ws_logger.info(f"🔌 用户断开连接: {self.client_id}, 原因: {reason}, 连接时长: {duration:.2f}秒")

    def log_reset(self, remote_address: str):
        """记录重置事件"""
        ws_logger.info(f"🧹 正在重置 WebSocket 连接: {remote_address}")

    def log_reset_error(self, error: str):
        """记录重置错误"""
        ws_logger.warning(f"⚠️ 关闭 WebSocket 时出错: {error}")

    def log_message_start(self, remote_address: str):
        """记录开始监听消息"""
        ws_logger.info(f"📥 开始监听消息: {remote_address}")

    def log_config_message(self, message_size: int):
        """记录配置消息"""
        self.msg_stats["config"] += 1
        ws_logger.debug(f"📋 配置消息 #{self.msg_stats['config']}: {message_size}字节")

    def log_control_message(self, message_size: int):
        """记录控制消息"""
        self.msg_stats["control"] += 1
        ws_logger.debug(f"🎛️ 控制消息 #{self.msg_stats['control']}: {message_size}字节")

    def log_audio_data(self, packet_count: int, total_bytes: int, show_progress: bool = False):
        """记录音频数据"""
        self.msg_stats["audio"] = packet_count
        self.audio_bytes_total = total_bytes

        if show_progress:
            # 使用 \r 进行进度显示，但不换行
            print(f"🎵 音频数据: {packet_count}包, 总计{total_bytes:,}字节", end="\r", flush=True)
        else:
            ws_logger.debug(f"🎵 音频数据: {packet_count}包, 总计{total_bytes:,}字节")

    def log_speech_detection(self, speech_start: bool, speech_end: bool = False):
        """记录语音检测事件"""
        if speech_start:
            ws_logger.info(f"🎤 检测到语音开始: {self.client_id}")
        if speech_end:
            ws_logger.info(f"🔇 检测到语音结束: {self.client_id}")

    def log_recognition_result(self, text: str, is_final: bool, mode: str, confidence: float = 0.0):
        """记录识别结果"""
        status = "最终" if is_final else "临时"
        ws_logger.info(f"📤 发送识别结果 → 客户端: \"{text}\" ({status}, 模式:{mode}, 置信度:{confidence:.2f})")

    def log_speaker_info(self, speaker_name: str, text: str, is_final: bool, mode: str):
        """记录说话人信息"""
        status = "最终" if is_final else "临时"
        ws_logger.info(f"📤 发送识别结果 → 客户端: [{speaker_name}] \"{text}\" ({status}, 模式:{mode})")

    def log_error(self, error: str, context: str = ""):
        """记录错误"""
        ws_logger.error(f"❌ WebSocket 错误 {context}: {error}")
        log_websocket_event("error", self.client_id, error=error, context=context)

    def log_warning(self, warning: str):
        """记录警告"""
        ws_logger.warning(f"⚠️ {warning}")

    def log_session_summary(self):
        """记录会话摘要"""
        duration = time.time() - self.start_time
        log_performance(
            "websocket_session",
            duration,
            client_id=self.client_id,
            config_messages=self.msg_stats["config"],
            audio_packets=self.msg_stats["audio"],
            control_messages=self.msg_stats["control"],
            total_bytes=self.audio_bytes_total
        )

        ws_logger.info(
            f"📊 会话统计 - 配置:{self.msg_stats['config']}条, "
            f"音频:{self.msg_stats['audio']}包({self.audio_bytes_total:,}字节), "
            f"控制:{self.msg_stats['control']}条, "
            f"时长:{duration:.2f}秒"
        )

    def log_model_operation(self, operation: str, model_name: str, **kwargs: object) -> None:
        """记录模型操作"""
        ws_logger.debug(f"🤖 模型操作 - {operation} {model_name}: {kwargs}")

    def log_processing_mode(self, mode: str):
        """记录处理模式"""
        ws_logger.debug(f"⚙️ 设置处理模式: {mode}")

    def log_chunk_config(self, chunk_size: list[int], chunk_interval: int):
        """记录分块配置"""
        ws_logger.debug(f"📦 分块配置 - 大小: {chunk_size}, 间隔: {chunk_interval}ms")


def create_websocket_logger(client_id: str) -> WebSocketLogger:
    """
    创建 WebSocket 日志管理器

    Args:
        client_id: 客户端标识

    Returns:
        WebSocketLogger 实例
    """
    return WebSocketLogger(client_id)


def log_websocket_performance(operation: str, duration: float, **kwargs: object) -> None:
    """
    记录 WebSocket 性能日志

    Args:
        operation: 操作名称
        duration: 执行时间
        **kwargs: 其他参数
    """
    log_performance(f"websocket_{operation}", duration, **kwargs)
